package com.itheima.advantagesup.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.advantagesup.common.PageBean;
import com.itheima.advantagesup.common.constant.CateDefaultDate;
import com.itheima.advantagesup.common.constant.MessageConstant;
import com.itheima.advantagesup.dto.YddCateDTO;
import com.itheima.advantagesup.entity.YddCate;
import com.itheima.advantagesup.exception.BusinessException;
import com.itheima.advantagesup.mapper.YddCateMapper;
import com.itheima.advantagesup.service.YddCateService;
import com.itheima.advantagesup.vo.YddCateVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: youdianda-1
 * @className: YddCateServiceImpl
 * @description: TODO
 * @author: xch
 * @createTime: 2023-07-27 10:22
 **/

@Service
public class YddCateServiceImpl implements YddCateService {

    @Autowired
    private YddCateMapper yddCateMapper;

    @Override
    public List<YddCate> getAllCate() {
        return yddCateMapper.selectAllCate();
    }

    @Override
    public PageBean<YddCateVO> getListCate(String catename, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        Page<YddCate> p = yddCateMapper.getListCate(catename);
        List<YddCate> list = p.getResult();
        List<YddCateVO> l1 = new ArrayList<>();
        for (YddCate yddCate : list) {
            YddCateVO y = new YddCateVO();
            y.setId(yddCate.getId());
            y.setCatename(yddCate.getCatename());
            y.setIcon(yddCate.getIcon());
            y.setSort_num(yddCate.getSortNum());
            l1.add(y);
        }

        return new PageBean<YddCateVO>((int) p.getTotal(), p.getPages(), limit, p.getPageNum(), l1);
    }

    @Override
    public void addCate(YddCateDTO yddCateDTO) {
        YddCate y = new YddCate();
        Integer count = yddCateMapper.getCateByName(yddCateDTO);
        if (count > 0) {
            throw new BusinessException(MessageConstant.NAME_ERROR);
        }
        BeanUtils.copyProperties(yddCateDTO, y);
        y.setSortNum(yddCateDTO.getSort_num());
        y.setDefaultDate(CateDefaultDate.DEFAULT_VALUE);
        yddCateMapper.insertCate(y);
    }

    @Override
    public void updateCate(YddCateDTO yddCateDTO) {
        YddCate y = new YddCate();
        Integer count = yddCateMapper.getCateIdAndByName(yddCateDTO);
        if (count > 0) {
            throw new BusinessException(MessageConstant.NAME_ERROR);
        }
        BeanUtils.copyProperties(yddCateDTO, y);
        y.setSortNum(yddCateDTO.getSort_num());
        yddCateMapper.updateCate(y);
    }

    @Override
    public YddCateVO getOneCate(String id) {
        return yddCateMapper.selectOneCate(id);
    }

    @Override
    public void deleteCate(String id) {
        yddCateMapper.deleteCate(id);
    }
}
